/**
 * 计算时间戳与当前时间的差值
 *  start_time 开始时间戳
 * 返回[year, month, day, hour, minute, second]的数组
 */
function calculateDiffTime(start_time, end_time) {
    var startTime = 0,
        endTime = 0
    let type = '';
    if (start_time < end_time) {
        startTime = start_time
        endTime = end_time
        type = "<"
    } else if (start_time > end_time) {
        startTime = end_time
        endTime = start_time
        type = ">"
    } else if (start_time == end_time) {
        startTime = end_time
        endTime = start_time
        type = "="

    }
    //计算天数
    var timeDiff = endTime - startTime;
    timeDiff = timeDiff / 1000;
    //console.log(timeDiff);

    var year = Math.floor(timeDiff / 86400 / 365);
    timeDiff = timeDiff % (86400 * 365);
    var month = Math.floor(timeDiff / 86400 / 30);
    timeDiff = timeDiff % (86400 * 30);
    var day = Math.floor(timeDiff / 86400);
    timeDiff = timeDiff % 86400;
    var hour = Math.floor(timeDiff / 3600);
    timeDiff = timeDiff % 3600;
    var minute = Math.floor(timeDiff / 60);
    timeDiff = timeDiff % 60;
    var second = timeDiff;
    return [year, month, day, hour, minute, second, type]

    // var timeDiff = endTime - startTime
    // var hour = Math.floor(timeDiff / 3600);
    // timeDiff = timeDiff % 3600;
    // var minute = Math.floor(timeDiff / 60);
    // timeDiff = timeDiff % 60;
    // var second = timeDiff;
    // return [hour, minute, second];

}

/**
 * 把上面的时间返回数组转化为字符串
 *  start_time 开始时间戳
 * 传入[year, month, day, hour, minute, second,type]的数组
 */
function caltoString(array) {
    let str = '';
    if (array != '') {
        if (array[0] != 0)
            str = str + array[0] + '年'
        if (array[1] != 0)
            str = str + array[1] + '月'
        if (array[2] != 0)
            str = str + array[2] + '日'
        if (array[3] != 0)
            str = str + array[3] + '时'
        if (array[4] != 0)
            str = str + array[4] + '分'
        if (array[5] != 0)
            str = str + array[5] + '秒'
    }

    return str;


}

//转换年月日方法
function getDate(format, str) {
    var oDate = new Date(str),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth() + 1,
        oDay = oDate.getDate(),
        oHour = oDate.getHours(),
        oMin = oDate.getMinutes(),
        oSec = oDate.getSeconds();
    let oTime;
    if (format == 'yyyy-mm-dd') {
        oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay); //最后拼接时间
    } else if (format == 'yyyy/mm/dd') {
        oTime = oYear + '/' + getzf(oMonth) + '/' + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSec); //最后拼接时间
    }
    return oTime;
};
//补0操作
function getzf(num) {
    if (parseInt(num) < 10) {
        num = '0' + num;
    }
    return num;
}

/*
  滚动条到底部的触发函数，解决各浏览器兼容性问题
*/
// 文档的总高度
function getScrollHeight() {
    var scrollHeight = 0,
        bSH = 0,
        dSH = 0;
    if (document.body) {
        bSH = document.body.scrollHeight;
    }
    if (document.documentElement) {
        dSH = document.documentElement.scrollHeight;
    }
    scrollHeight = (bSH - dSH > 0) ? bSH : dSH;
    return scrollHeight;
}

// 滚动条在Y轴上的滚动距离
function getScrollTop() {
    var scrollTop = 0,
        bodyScrollTop = 0,
        documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

// 浏览器视口的高度
function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

// 验证邮箱的校验规则
let checkEmail = (rule, value, callback) => {
    const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    if (regEmail.test(value)) {
        return callback();
    }
    callback(new Error("请输入合法的邮箱！"));
};
// 验证手机号的校验规则
let checkMobile = (rule, value, callback) => {
    const regMobile = /^1[3-9][0-9]{9}$/;
    if (regMobile.test(value)) {
        return callback();
    }
    callback(new Error("请输入正确的手机号码！"));
};
// 验证身份证号的校验规则
let IDCard = (rule, value, callback) => {
    const regIDCard = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/;
    if (regIDCard.test(value)) {
        return callback();
    }
    callback(new Error("请输入正确的身份证号！"));
};

/*
  防抖函数
  func:函数
  wait：隔一段时间触发
  immediate：true:刚刚进入立即触发；false刚刚进入不会立即触发
*/
function debounce(func, wait, immediate) {
    //console.log("触发防抖");
    let timer, result;
    let debounced = function () {
        // 改变函数内部this指向
        let context = this;
        // event指向问题
        let args = arguments;
        if (timer) clearTimeout(timer);
        if (immediate) {
            // console.log("12312");
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null;
                // console.log(timer);
            }, wait)
            // 立即执行
            if (callNow) result = func.apply(context, args);
            // console.log(callNow);
        } else {
            //console.log("延时");
            timer = setTimeout(() => {
                func.apply(context, args);
            }, wait)
        }
        return result;
    }
    debounced.cancel = function () {
        clearTimeout(timer);
        timer = null;
    }
    return debounced;
}

/*
  节流函数
  有头有尾，可以第一次进入不触发，最后一次也不触发，结合时间戳和延迟定时器两者的方法
*/
function throttle(func, wait, options) {
    let context, args, timeout;
    // 时间戳
    let old = 0;
    if (!options) options = {};
    let later = function () {
        old = new Date().valueOf();
        timeout = null;
        func.apply(context, args);
    }
    return function () {
        context = this;
        args = arguments;
        // 获取当前的时间戳
        let now = new Date().valueOf();
        if (options.leading === false && !old) {
            old = now;
        }
        if (now - old > wait) {
            // 第一次会立即执行
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            // 立即执行
            func.apply(context, args);
            // console.log(old,now);
            old = now;
        } else if (!timeout && options.trailing !== false) {
            // 最后一次也会执行
            timeout = setTimeout(later, wait)
        }
    }
}

/*
  正则表达式，匹配只输出整数或者浮点数
  value:传入的值
*/
function numberReg(value) {
    const m = value.replace(/[^0-9.]/g, "")
        .replace(".", "#*")
        .replace(/\./g, "")
        .replace("#*", ".");
    return m;
}

// 对象数组升序函数:property:属性名，属性值为数字类型
function compare(property) {
    return function (obj1, obj2) {
        var value1 = obj1[property];
        var value2 = obj2[property];
        return value1 - value2;
    }
}

/**
 * @param key:键名
 * @param value:键值,
 * @param t(天数):过期时间，不写就不设置expires属性，cookie在浏览器关闭后删除
 */
function setCookie(key, value, t) {
    var oDate = new Date();
    oDate.setDate(oDate.getDate() + t);
    document.cookie = key + "=" + encodeURIComponent(value) + ";expires=" + oDate.toUTCString();
    /* if(getCookie(key)){
      // alert('设置成功');
    }else{
      alert('设置失败');
    } */
}
// 读取cookie 返回一个包含cookie键值对的对象
function getCookie(key) {
    var str = document.cookie.replace(/;\s*/ig, ';');
    var cookieArr = str.split(';');
    var cookieObj = {};
    var len = cookieArr.length;
    for (var i = 0; i < len; i++) {
        var item = cookieArr[i];
        var k = item.split('=')[0];
        var v = item.split('=')[1];
        cookieObj[k] = v;
    }
    if (cookieObj[key]) {
        return decodeURIComponent(cookieObj[key]);
    } else {
        return false;
    }
}

// 移除cookie，expires设置的是过期时间，如果这个过期时间是在过去，说明这个cookie已经不会再发送到服务器，随后浏览器会把cookie删除的
function removeCookie(key) {
    document.cookie = key + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    if (!getCookie(key)) {
        // alert('删除成功');
    } else {
        alert('删除失败');
    }
}

/*
  a. 缓存在localStorage或sessionStorage
  b. 如果浏览器不支持storage，则将数据存储在DOM元素中（如input元素）(这个没写)
*/
/**
 * 设置缓存值
 * @param key 主键
 * @param value 值
 * @param storageType 缓存类型，{1: sessionStorage , 2: localStorage }
 */
function setStorage(key, value, storageType) {
    if (Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]') {
        value = JSON.stringify(value);
    }
    if (!!storageType && storageType === 1) {
        sessionStorage.setItem(key, value);
    } else {
        localStorage.setItem(key, value);
    }
}

/**
 * 获取缓存
 * @param key 主键
 * @param storageType 缓存类型，{1: sessionStorage , 2: localStorage }
 * @param isJSON 是否返回JSON，{true: 返回对象 , false: 返回String }
 * @returns {*}
 */
function getStorage(key, storageType, isJSON) {
    var value;
    if (!!storageType && storageType === 1) {
        value = sessionStorage.getItem(key);
    } else {
        value = localStorage.getItem(key);
    }
    if (!!isJSON) {
        try {
            value = JSON.parse(value);
        } catch (err) {
            console.warn('value is not a JSON string =>', err);
        }
    }
    return value;
}

/**
 * 删除缓存
 * @param key 主键
 * @param storageType 缓存类型，{1: sessionStorage , 2: localStorage }
 */
function removeStorage(key, storageType) {
    if (!!storageType && storageType === 1) {
        sessionStorage.removeItem(key);
    } else {
        localStorage.removeItem(key);
    }
}

/**
 * 判断数值是否在某个范围内，返回Boolean
 * @param num  数据中的值
 * @param m    最小值
 * @param n    最大值
 */
function numRange(num, m, n) {
    var re = /(\d+)/g;
    while (re.exec(num)) {
        var int = parseInt(RegExp.$1);
        if (int < m || int > n) return false;
    }
    return true;
}

/**
 * 将Number类型转换为字符串类型，并且以千位分隔符显示,例如: 1,000,000.00
 * @param num Number类型
 */
function thousandsSeparated(num) {
    if (typeof num === "number") {
        num = num.toFixed(2);
        let smallNum = num.toString().split(".")[1];
        let num1 = num.toString().split(".")[0];
        if (smallNum === undefined) {
            smallNum = "00";
        } else if (smallNum.length === 1) {
            smallNum = smallNum + "0";
        }

        return num1.replace(/(?=(\B\d{3})+(\.|$))/g, ",") + "." + smallNum;
    } else {
        return "0";
    }
}

/**
 * 将字符串类型转换为数字类型，移除千位分隔符，还原Number类型
 * @param str 字符串类型
 */
function toNumber(str) {
    if (str === "") {
        return "";
    }
    if (str === undefined) {
        return ""
    }
    if (str[str.length - 1] === "元") {
        str = str.substr(0, str.length - 1)
    }
    return Number(str.replace(/,/g, ""));
}

/**
 * 判断鼠标是否在指定的元素（div）内
 * @param id 类名
 */
function judgeMouseIn(id) {
    var wx = window.event.clientX;
    var wy = window.event.clientY;
    var d_left = document.querySelector(id).offsetLeft;
    var d_top = document.querySelector(id).offsetTop;
    var d_width = document.querySelector(id).clientWidth;
    var d_height = document.querySelector(id).clientHeight;
    if (wx < d_left || wy < d_top || wx > (d_left + d_width) || wy > (d_top + d_height))
        return false;
    else
        return true;
}

// 深度克隆方法
function deepClone(data) {
    const type = judgeType(data);
    let obj;
    if (type === 'array') {
        obj = [];
    } else if (type === 'object') {
        obj = {};
    } else {
        // 不再具有下一层次
        return data;
    }
    if (type === 'array') {
        // eslint-disable-next-line
        for (let i = 0, len = data.length; i < len; i++) {
            obj.push(deepClone(data[i]));
        }
    } else if (type === 'object') {
        // 对原型上的方法也拷贝了....
        // eslint-disable-next-line
        for (const key in data) {
            obj[key] = deepClone(data[key]);
        }
    }
    return obj;
}

function judgeType(obj) {
    // tostring会返回对应不同的标签的构造函数
    const toString = Object.prototype.toString;
    const map = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]': 'null',
        '[object Object]': 'object',
    };
    if (obj instanceof Element) {
        return 'element';
    }
    return map[toString.call(obj)];
}

// 判断两个数组是否相等：[1,2,3], [2,1,3]
function isArrayEqual(value1 = [], value2 = []) {
    if (value1.length === value2.length) {
        for (let i = 0; i < value1.length; i++) {
            const index = value2.indexOf(value1[i]);
            if (index > -1) {
                value2.splice(index, 1);
            } else {
                return false;
            }
        }

        return true;
    }

    return false;
}

// 对比两个数组，返回差异值的下标  [1,2,3,5] [1,2,3,4,5]
function isArraydifference(value1 = [], value2 = []) {
    let num = 0
    let arrlong = []
    let arrshort = []
    if (value1.length > value2.length) {
        num = value1.length
        arrlong = value1
        arrshort = value2
    } else {
        num = value2.length
        arrlong = value2
        arrshort = value1
    }
    for (let i = 0; i < num; i++) {
        if (arrshort.indexOf(arrlong[i]) === -1) {
            return i;
        }
    }

    return -1;
}

// 判断输入的字符是否为中文
function IsChinese(fieldid) {
    let str = fieldid.trim();
    if (str.length != 0) {
        let reg = /^[\u4e00-\u9fa5]+$/;
        if (!reg.test(str)) {
            return false;
        }
    }
    return true;
}

// 判断输入的字符是否为英文字母,返回true是英文
function IsLetter(fieldid) {
    let str = fieldid.trim();
    str = str.toLowerCase();
    if (str.length != 0) {
        let reg = /^[a-zA-Z]+$/;
        if (!reg.test(str)) {
            return false;
        }
    }
    return true;
}

/*
  实现拼音搜索和汉字搜索的方法
  backUpArr：备份的数据
  val:搜索关键字
  l:需要搜索的后端字段命名
*/
const pinyin = require('pinyin-match');
function searchMethod(backUpArr, val, l = "personname") {
    // console.log('backUpArr, val, l: ', backUpArr, val, l);
    if (val.trim() !== "") {
        let result = [];
        backUpArr.forEach((item) => {
            let m = pinyin.match(item[l].trim(), val.trim());
            if (m) {
                result.push(item);
            }
        });
        // console.log(result);
        return result;
    } else {
        // console.log(backUpArr);
        return backUpArr;
    }
}

/*
  根据对象数组中对象属性值的不同将数组进行分组
  initialArr：传入的数组
  pro:某个对象属性，用来分组
*/
function formateArrData(initialArr, pro) {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
        return "请传入正确格式的数组";
    }
    if (!pro) {
        return "请传入对象属性";
    }
    return initialArr.reduce((acc, item) => {
        let currentVal = item[pro];
        if (!acc[currentVal]) {
            acc[currentVal] = [];
        }
        acc[currentVal].push(item);
        return acc;
    }, {});
}

/*
  数组去重(引用类型去重)
  arr:需要去重的数组
  name:根据某个字段来去重，字符串类型
*/
function arrayDeduplication(arr, name) {
    let hash = {};
    arr = arr.reduce(function (item, next) {
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
        return item
    }, []);
    return arr;
}

/**
 * 将数组转换成map方便调用
 */
function arrayTomap(arr, key, value) {
    if (!(arr instanceof Array)) {
        return [];
    }
    if (key === "") {
        return [];
    }
    if (value === "") {
        return [];
    }
    if (arr.length === 0) {
        return [];
    }
    var dataMap = new Map();
    arr.forEach((v, i) => {
        dataMap.set(v[key], v[value])
    })
    return dataMap;
}

/*
  数组去重(引用类型去重)
  personname:要确定的，写死的
*/
function arrayDeduplication2(arr) {
    let hash = {};
    arr = arr.reduce(function (item, next) {
        hash[next.psnname] ? '' : hash[next.psnname] = true && item.push(next);
        return item
    }, []);
    return arr;
}

/*
  数学表达式计算
  逆波兰表达式求值
*/
// 递归处理数组中的对象和数组，将数组并到对象下，作为对象的属性值
/* function recursionObjArrMethod(list,arr){
  list.forEach(v=>{
    let obj={};
    for(let key in v["epmsDocFolderEntity"]){
      obj[key]=v["epmsDocFolderEntity"][key];
      if(key==="folderid"){
        obj["value"]=v["epmsDocFolderEntity"][key];
      }else if(key==="foldername"){
        obj["label"]=v["epmsDocFolderEntity"][key];
      }

    }
    obj["children"]=v.subDocList;
    arr.push(obj);
    if(obj.children!==null&&obj.children.length>0){
      let arr01=[];
      arr01=recursionObjArrMethod(obj.children)
    }
  });
  return arr;
} */

// 直接下载文件，而不是打开预览
function downloadUrlFile(url, name) {
    url = url.replace(/\\/g, '/');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
    xhr.onload = () => {
        if (xhr.status === 200) {
            // 获取文件blob数据并提交
            saveAs(xhr.response, name);
        }
    };

    xhr.send();
}
function saveAs(data, name) {
    var urlObject = window.URL || window.webkitURL || window;
    var export_blob = new Blob([data]);
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = urlObject.createObjectURL(export_blob);
    save_link.download = name;
    save_link.click();
}

/*
    封装校验表单的方法
    formName:ref元素名称,字符串
    resultArr：本组件保存校验结果的字段名,字符串
    instanc：vue实例
*/
function checkFormMethod(formName, resultArr, instance) {
    // console.log('formName: ', formName);
    let _self = instance;
    let result = new Promise(function (resolve, reject) {
        _self.$refs[formName].$refs["formRef"].validate((valid) => {
            if (valid) {
                resolve();
            } else {
                _self.$toast("请填写必填内容", 3500);
                setTimeout(() => {
                    var isError = document.getElementsByClassName("is-error");
                    isError[0].querySelector("input").focus();
                }, 100);
                reject();
            }
        });
    });
    _self[resultArr].push(result); //push 得到promise的结果
}

// 判断是对象还是数组，是对象返回"object",数组返回 "array"
function isObjArr(value) {
    if (Object.prototype.toString.call(value) === "[object Array]") {
        //    console.log('value是数组');
        return "array";
    } else if (Object.prototype.toString.call(value) === '[object Object]') {
        //    console.log('value是对象');
        return "object";
    } else {
        //  console.log('value不是数组也不是对象')
    }
}

// 生成表单的对象处理方法
function formGeneratorMethod(formData) {
    let baseInfo = {
        //所有后端指定字段
        form: {},
        //所有字段的校验规则,可以引入自定义校验规则，参考element
        rules: {},
        formDisable: formData.disabled, //是否禁用整个表单
        refName: formData.formRef, //ref字段名
        // labelW: formData.labelWidth+"px", //左侧标签宽度
        labelW: "130px", //左侧标签宽度
        labelP: formData.labelPosition, //左侧标签位置
        formStyle:
            "display: flex;justify-content: space-between;flex-wrap: wrap;margin-left: 15px;", //el-form内置样式
        // 传给组件的重要数组，根据这个数组生成表单
        itemList: []
    };
    formData.fields.forEach(item => {
        let itemObj = {
            show: true,
            itemClass: "",
            inputClass: "",
            selectClass: "width-class",
            cascaderClass: "width-class",
            label: "",
            id: null,
            name: item.__vModel__,
            prop: "",
            type: item.__config__.tagIcon,
            typeOptions: "",
            isTextarea: item.__config__.tagIcon === "textarea",
            separator: item.separator !== undefined ? item.separator : ">>",
            cascaderProps: {
                expandTrigger: "hover",
                value: "value",
                label: "label",
                children: "children",
                multiple: false,
            },
            selectList: item.__slot__ !== undefined ? item.__slot__.options : [],
            backUpSelectList: item.__slot__ !== undefined ? item.__slot__.options : [],
            selectType: "",
            multiple: item.multiple,
            filterable: item.filterable,
            valueType: "object",
            noDataText: "加载中",
            selectLoadMore: item.__config__.label.includes("人"),
            selectOnOff: false,
            selectMethod: "getAllApplicationMans",
            selectKeyWord: "",
            placeholder: item.placeholder,
            disabled: false,
            generateStr: "",
            suffix: "",
            suffixClass: "",
            dateType: "",
            startText: "开始日期",
            endText: "结束日期",
            clearable: item.clearable,
            dateFormat: item["value-format"] ? item["value-format"] : "yyyy-MM-dd",
            inputFormat: item.format ? item.format : "yyyy-MM-dd",
            dateClass: "date-icon",
            deleteCount: 1,
            step: item.step,
            showStops: item["show-stops"],
            min: item.min,
            max: item.max,
            range: item.range,
            selectableRange: item["picker-options"],
            "start-placeholder": item["start-placeholder"],
            "end-placeholder": item["end-placeholder"],
            "is-range": item["is-range"],
            "range-separator": item["range-separator"],
        };
        // 处理类名和标签名生成 itemClass label
        if (item.__config__.label.length === 6) {
            itemObj.itemClass = `${item.__config__.span === 24 ? 'width-class' : 'item-class'} six-label month-item`;
            itemObj.label = `${item.__config__.label}：`;
        } else if (item.__config__.label.length === 5) {
            itemObj.itemClass = `${item.__config__.span === 24 ? 'width-class' : 'item-class'} five-label month-item`;
            itemObj.label = `${item.__config__.label}：`;
        } else if (item.__config__.label.length === 4) {
            itemObj.itemClass = `${item.__config__.span === 24 ? 'width-class' : 'item-class'} four-label month-item`;
            itemObj.label = `${item.__config__.label}：`;
        } else if (item.__config__.label.length === 3) {
            itemObj.itemClass = `${item.__config__.span === 24 ? 'width-class' : 'item-class'} three-label colon month-item`;
            itemObj.label = `${item.__config__.label}`;
        } else if (item.__config__.label.length === 2) {
            itemObj.itemClass = `${item.__config__.span === 24 ? 'width-class' : 'item-class'} two-label colon month-item`;
            itemObj.label = `${item.__config__.label}`;
        }

        // 处理输入框类型 type selectList backUpSelectList dateType
        if (item.__config__.tagIcon === "date") {
            itemObj.type = "datepicker";
            itemObj.dateType = item.type;
        } else if (item.__config__.tagIcon === "date-range") {
            itemObj.type = "datepicker";
            itemObj.dateType = item.type;
        } else if (item.__config__.tagIcon === "textarea") {
            itemObj.type = "input";
            itemObj.itemClass += " class-textarea";
        } else if (item.__config__.tagIcon === "cascader") {
            itemObj.selectList = item.options;
            itemObj.backUpSelectList = item.options;
        } else if (item.__config__.tagIcon === "time") {
            item["picker-options"].format = item.format;
        } else if (item.__config__.tagIcon === "time-range") {
            itemObj.type = "time";
        }

        // 表单对象字段回显
        baseInfo.form[item.__vModel__] = "";
        // 多选框绑定值类型一定是数组
        if (item.__config__.tagIcon === "checkbox") {
            baseInfo.form[item.__vModel__] = [];
        } else if (item.__config__.tagIcon === "slider") {//滑块绑定值必须为0
            baseInfo.form[item.__vModel__] = 0;
            itemObj.itemClass = itemObj.itemClass.replace(" month-item", "");
        }

        // 是否必填的处理 rules prop
        if (item.__config__.required) {
            itemObj.prop = item.__vModel__;
        }
        let tempRulesStr = "请填写";
        if (item.required && (item.__config__.tagIcon === "time" || item.__config__.tagIcon === "date-range" || item.__config__.tagIcon === "select")) {
            // 请选择
            tempRulesStr = "请选择";
        }
        baseInfo.rules[item.__vModel__] = [
            { required: true, message: `${tempRulesStr}${item.__config__.label}`, trigger: ["blur", "change"] }
        ];

        baseInfo.itemList.push(itemObj);
    });

    return baseInfo;
}

// 回显数据时所有占位符变为空串，点击编辑按钮时复原占位符文字
function echoPlaceholderMethod(data) {
    if (data.formDisable) {//禁用状态，占位符是空串
        data.itemList.forEach(item => {
            item.placeholder = "";
        });
    } else {//可编辑表单，占位符复原文本
        data.itemList.forEach(item => {
            let text = "请选择";
            if (item.type === "input") {
                text = "请填写";
            }
            item.placeholder = `${text}${item.label}`;
            item.placeholder = item.placeholder.replace("：", "");
        });
    }
}

/*
    查找当前索引，并且删除当前对象(常用),或者数组末尾新增对象(偶尔针对某些地方使用)
    arr：当前数组，
    str1:当前数组中对象的键
    str2：比对的值，
    flag：true:删除当前对象， false：数组末尾新增对象
    str3,str4:备选参数, flag为false那么必传
*/
function findIndexAndSplice(arr, str1, str2, flag, str3, str4) {
    let i = arr.findIndex(v => v[str1] === str2);
    if (flag) {//删除当前对象
        if (i !== -1) {
            arr.splice(i, 1);
        }
    } else {//数组末尾新增对象
        if (i === -1) {
            arr.push({
                [str1]: str2,
                [str3]: str4,
            });
        };
    }
}

/* 
  动态拼接参数到请求的url方法
*/
function urlQueryMethod(queryConfig) {
    let str = "";
    for (let o in queryConfig) {
        str += o + "=" + queryConfig[o] + "&";
    }
    str = str.substring(0, str.length - 1);
    return str;
}

// 拆封url后面?拼接的键值参数的方法
function splitUrlMethod(path) {
    // console.log('path: ', path);
    let firsturl = path.split('?');
    let urlobj = {};
    let secondurl = firsturl[1].split('&');
    for (let i = 0; i < secondurl.length; i++) {
        let thirdurl = secondurl[i].split('=');
        urlobj[thirdurl[0]] = thirdurl[1];
    }
    return urlobj;
}

// 分钟数转换为 小时：分钟 
function ChangeHourMinutestr(str,flag=true) {
    if (str !== "0" && str !== "" && str !== null) {
        if(flag){
            let arr=[((Math.floor(str / 60)).toString().length < 2 ? "0" + (Math.floor(str / 60)).toString() :
            (Math.floor(str / 60)).toString()),((str % 60).toString().length < 2 ? "0" + (str % 60).toString() : (str % 60).toString())];
            return  arr;
        }else{
            let arr=[(Math.floor(str / 60)).toString(),(str % 60).toString()];
            return  arr;
        }
    }
    else {
        return "";
    }
}

export {
    calculateDiffTime,
    caltoString,
    getDate,
    getScrollHeight,
    getScrollTop,
    getWindowHeight,
    checkEmail,
    checkMobile,
    IDCard,
    debounce,
    throttle,
    numberReg,
    compare,
    numRange,
    thousandsSeparated,
    toNumber,
    setStorage,
    getStorage,
    judgeMouseIn,
    deepClone,
    isArrayEqual,
    IsChinese,
    IsLetter,
    searchMethod,
    formateArrData,
    arrayDeduplication,
    isArraydifference,
    downloadUrlFile,
    arrayTomap,
    arrayDeduplication2,
    checkFormMethod,
    exportExcel,
    isObjArr,
    formGeneratorMethod,
    echoPlaceholderMethod,
    findIndexAndSplice,
    urlQueryMethod,
    splitUrlMethod,
    ChangeHourMinutestr,
};
